package com.example.personblog.service;

import com.example.personblog.common.ResultEnum;
import com.example.personblog.entity.Comment;
import com.example.personblog.exception.BusinessException;
import com.example.personblog.repository.CommentRepository;
import com.example.personblog.repository.PostRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class CommentService {
    
    @Autowired
    private CommentRepository commentRepository;
    
    @Autowired
    private PostRepository postRepository;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String COMMENT_LIKE_KEY = "comment:like:";
    
    /**
     * 分页获取文章评论
     */
    public Page<Comment> getCommentsByPostId(Long postId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("createTime").descending());
        return commentRepository.findByPostId(postId, pageable);
    }
    
    /**
     * 获取用户的所有评论
     */
    public List<Comment> getUserComments(Long userId) {
        return commentRepository.findByUserIdOrderByCreateTimeDesc(userId);
    }
    
    /**
     * 创建评论
     */
    @Transactional(rollbackFor = Exception.class)
    public Comment createComment(Comment comment) {
        // 检查文章是否存在
        if (!postRepository.existsById(comment.getPostId())) {
            throw new BusinessException(ResultEnum.POST_NOT_EXIST);
        }
        return commentRepository.save(comment);
    }
    
    /**
     * 删除评论
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteComment(Long id, Long userId) {
        Comment comment = commentRepository.findById(id)
                .orElseThrow(() -> new BusinessException(ResultEnum.COMMENT_NOT_EXIST));
        
        // 检查是否是评论作者
        if (!comment.getUserId().equals(userId)) {
            throw new BusinessException(ResultEnum.COMMENT_NO_PERMISSION);
        }
        
        commentRepository.deleteById(id);
    }
    
    /**
     * 批量删除文章的所有评论
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteCommentsByPostId(Long postId, Long userId) {
        // 检查是否是文章作者
        if (!postRepository.existsByIdAndUserId(postId, userId)) {
            throw new BusinessException(ResultEnum.POST_NO_PERMISSION);
        }
        commentRepository.deleteByPostId(postId);
    }
    
    /**
     * 获取评论数量
     */
    public Long getCommentCount(Long postId) {
        return commentRepository.countByPostId(postId);
    }
    
    /**
     * 获取最新评论
     */
    public List<Comment> getLatestComments(int limit) {
        Pageable pageable = PageRequest.of(0, limit, Sort.by("createTime").descending());
        return commentRepository.findLatestCommentsWithUser(pageable);
    }
    
    /**
     * 检查评论权限
     */
    public boolean checkCommentPermission(Long commentId, Long userId) {
        return commentRepository.existsByIdAndUserId(commentId, userId);
    }
    
    /**
     * 分页获取用户评论
     */
    public Page<Comment> getUserCommentsByPage(Long userId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("createTime").descending());
        return commentRepository.findByUserId(userId, pageable);
    }
    
    /**
     * 点赞/取消点赞评论
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean toggleLike(Long commentId, Long userId) {
        String key = COMMENT_LIKE_KEY + commentId;
        Boolean isMember = redisTemplate.opsForSet().isMember(key, userId.toString());
        
        if (Boolean.TRUE.equals(isMember)) {
            // 取消点赞
            redisTemplate.opsForSet().remove(key, userId.toString());
            commentRepository.decrementLikes(commentId);
            return false;
        } else {
            // 点赞
            redisTemplate.opsForSet().add(key, userId.toString());
            commentRepository.incrementLikes(commentId);
            return true;
        }
    }
    
    /**
     * 获取评论点赞状态
     */
    public boolean getLikeStatus(Long commentId, Long userId) {
        String key = COMMENT_LIKE_KEY + commentId;
        return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, userId.toString()));
    }
    
    /**
     * 获取评论点赞数
     */
    public Long getLikeCount(Long commentId) {
        String key = COMMENT_LIKE_KEY + commentId;
        Long count = redisTemplate.opsForSet().size(key);
        return count != null ? count : 0L;
    }
} 